package myky.com.doctorapp.ui

import android.graphics.Color
import android.os.Bundle
import android.support.v4.widget.NestedScrollView
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.OrientationHelper
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.facebook.drawee.view.SimpleDraweeView
import com.github.nukc.stateview.Constant
import com.gyf.barlibrary.ImmersionBar
import kotlinx.android.synthetic.main.activity_doctor_details.*
import myky.com.doctorapp.R
import myky.com.doctorapp.adapter.DoctorVisitedAdapter
import myky.com.doctorapp.adapter.TeamInfoAdapter
import myky.com.doctorapp.api.Address
import myky.com.doctorapp.base.BaseActivity
import myky.com.doctorapp.contract.DoctorDeatailsContract
import myky.com.doctorapp.entity.DoctorEntity
import myky.com.doctorapp.entity.ImageParamBean
import myky.com.doctorapp.entity.TeamEntity
import myky.com.doctorapp.entity.UMShareEntity
import myky.com.doctorapp.presenter.DoctorDeatailsPresenter
import myky.com.doctorapp.utils.*
import myky.com.doctorapp.wight.RecycleViewDivider
import java.util.*
import kotlin.collections.ArrayList


/**
 * Title:医生详情
 * Description: TODO
 * @author xiangyao
 * date 2019/1/29
 */
class DoctorDetailsActivity : BaseActivity<DoctorDeatailsPresenter, DoctorEntity.PayLoadEntity>(), DoctorDeatailsContract.View {

    var isOpen_stop = false

    private lateinit var strings: MutableList<Array<String>>

    var doctorId = 0

    private lateinit var header: SimpleDraweeView

    lateinit var doctorVisitedAdapter: DoctorVisitedAdapter

    private val doctorVisits = ArrayList<DoctorEntity.PayLoadEntity.DoctorvisitsEntity>()

    lateinit var teamInfoAdapter: TeamInfoAdapter

    private lateinit var teamEntityList: MutableList<TeamEntity.DataEntity>




    override fun showTeams(mTeamEntityList: MutableList<TeamEntity.DataEntity>) {
        if (mTeamEntityList.size > 0) {
            teamEntityList.addAll(mTeamEntityList)
            teamInfoAdapter.notifyDataSetChanged()
        } else {
            bespeak_info_affiliatedTeam_layout.visibility = View.GONE
        }
    }


    override fun reloadActivity() {


    }

    override fun injectTarget(): View = findViewById(R.id.injectView)

    override fun initData() {

        val extras = intent.extras

        doctorId = extras.getInt(Constants.DOCTORID,0)

        mPresenter.getDoctorDeatails(doctorId.toString(), "v2.0")

        mPresenter.getTeamInfo("v1.0", doctorId.toString())


    }

    override fun getPresenter(): DoctorDeatailsPresenter = DoctorDeatailsPresenter()

    private var isOpen_good: Boolean = false

    override fun initView() {


        ImmersionBar.with(this)
                .statusBarColor(R.color.colorPrimary)
                .titleBar(R.id.my_self_title)
                .init()

        header = findViewById(R.id.bespeak_info_header)

        bespeak_good_at.setOnClickListener {
            if (isOpen_good) {
                bespeak_experience_tv.visibility = View.GONE
                bespeak_good_at_tv.maxLines = 3
                bespeak_iv_good_at.background = resources.getDrawable(R.drawable.yyghlb_xjt)
                isOpen_good = false
            } else {
                bespeak_experience_tv.visibility = View.VISIBLE
                bespeak_good_at_tv.maxLines = 10000
                bespeak_iv_good_at.background = resources.getDrawable(R.drawable.yyghlb_xjt_xs)
                isOpen_good = true
            }

        }

        bespeak_info_stop_hint_iv.setOnClickListener {

            if (isOpen_stop) {
                bespeak_info_stop_hint.visibility = View.GONE
                bespeak_info_stop_hint_iv.setImageResource(R.drawable.xx)
                isOpen_stop = false
            } else {
                bespeak_info_stop_hint.visibility = View.VISIBLE
                bespeak_info_stop_hint_iv.setImageResource(R.drawable.xs)
                isOpen_stop = true
            }
        }

        backLayout.setOnClickListener { finish() }

        bespeak_info_kf.setOnClickListener {
            goToCustomService(this)

        }

        shareLayout.setOnClickListener {

            var umShareEntity = UMShareEntity()

            umShareEntity.shareWebUrl = "${Address.H5_URL}#/doctorDetail?doctorid=$doctorId"
            umShareEntity.shareTitle = "TEST"
            umShareEntity.shareDeascrebe = "TEST"
            umShareEntity.shareImageUrl = "https://www.baidu.com/img/bd_logo1.png?where=super"



            UMShareUtils.showShareDialog(this, umShareEntity, object : UMShareUtils.ShareStatesCallback {
                override fun shareSucees() {
                }

                override fun shareFailed(message: String?) {
                    Log.v("xiangyao", message)
                }
            })

        }
        bespeak_info_remote.setOnClickListener {

            val bundle=Bundle()
            bundle.putInt(Constants.DOCTORID,doctorId)
            startActivity(RemoteSubmitActivity::class.java,bundle)
        }
        bespeak_info_consult.setOnClickListener {

            val bundle=Bundle()
            bundle.putInt(Constants.DOCTORID,doctorId)
            startActivity(ExpertConsultActivity::class.java,bundle)
        }


        /**
         * title 滑动显示和隐藏
         *
         * 滑动区间 doctor_bg
         * */
        nested_scrollview.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->

            val bottom = doctor_bg.bottom
            var total = 0
            total += scrollY

            when {
                total <= 0 -> titleText.setTextColor(Color.argb(0, 255, 255, 255))
                bottom >= total -> {
                    val d = total.toDouble() / bottom
                    val alpha = d * 255
                    titleText.setTextColor(Color.argb(alpha.toInt(), 255, 255, 255))
                }
                else -> titleText.setTextColor(Color.argb(255, 255, 255, 255))
            }

        })



        initDoctorScadule()

    }

    /**
     *初始化医生的出诊时间表
     * */
    private fun initDoctorScadule() {


        doctorVisits.clear()
        for (i in 0..7) {
            doctorVisits.add(DoctorEntity.PayLoadEntity.DoctorvisitsEntity())
        }
        strings = Arrays.asList(resources.getStringArray(R.array.visit_time))

        teamEntityList = ArrayList()

        recycler_visit_time.isNestedScrollingEnabled = false
        val layoutManager = GridLayoutManager(this, 8)
        recycler_visit_time.layoutManager = layoutManager
        recycler_visit_time.overScrollMode = View.OVER_SCROLL_NEVER


        val linearlayoutmanager = LinearLayoutManager(this)
        group_team_rl.layoutManager = linearlayoutmanager
        //解决scrollview和recycler滑动冲突
        group_team_rl.isNestedScrollingEnabled = false
        layoutManager.orientation = OrientationHelper.VERTICAL
        group_team_rl.addItemDecoration(RecycleViewDivider(this, OrientationHelper.VERTICAL, 0, Color.BLUE))
        group_team_rl.itemAnimator = DefaultItemAnimator()
        group_team_rl.overScrollMode = View.OVER_SCROLL_NEVER

        doctorVisitedAdapter = DoctorVisitedAdapter(doctorVisits, strings)
        recycler_visit_time.adapter = doctorVisitedAdapter


        teamInfoAdapter = TeamInfoAdapter(teamEntityList)
        group_team_rl.adapter = teamInfoAdapter

        teamInfoAdapter.setOnItemChildClickListener { _, _, position ->


            val data = teamInfoAdapter.data

            val institutionid = data[position].institutionid


            val type = data[position].type

            when (type) {

                0 -> {

                    var bundle = Bundle()

                    bundle.putInt(Constants.TEAMID, institutionid)


                    startActivity(DoctorTeamActivity::class.java, bundle)

                }
//h5 团队
                1 -> {
                    ToastUtils.show("H5团队")
                }
            }


        }
    }

    override fun getContenView(): Int = R.layout.activity_doctor_details

    override fun showDataSuccess(datas: DoctorEntity.PayLoadEntity) {


    }

    override fun showDoctorDeatails(doctorDeatails: DoctorEntity.PayLoadEntity) {

        bespeak_info_realName.text = doctorDeatails.realname

        header.setImageURI(UriUtils.getUriInstance().getUri(Constant.ONLINEPIC, Address.IMAGE + doctorDeatails.headPhoto))

        bespeak_info_hospital.text = doctorDeatails.hospitalname

        bespeak_info_ks.text = doctorDeatails.departmentname

        bespeak_info_level.text = resources.getStringArray(R.array.administrationName_level)[doctorDeatails.administrationname]

        bespeak_info_level_tb.text = resources.getStringArray(R.array.academicName_level)[doctorDeatails.academicname]

        bespeak_good_at_tv.text = "专业擅长: ${doctorDeatails.speciality}"

        bespeak_experience_tv.text = "职业经历: \r\n ${doctorDeatails.experience}"

        bespeak_info_hospital_ads.text = doctorDeatails.address

        val beginDay = doctorDeatails.beginday
        val endDay = doctorDeatails.endday
        val dayStatus = resources.getStringArray(R.array.visit_daystatus_time)


        if (beginDay != null && endDay != null) {
            val beginTime = doctorDeatails.unvisitbegintime
            val endTime = doctorDeatails.unvisitendtime
            if (beginTime == endTime) {

                bespeak_info_stop.text = "${SystemUtil.getText_Date(beginTime)}   ${dayStatus[doctorDeatails.daystatusone]} 停诊"
            } else {
                val start = SystemUtil.getText_Date(beginTime) + " " + dayStatus[doctorDeatails.daystatusone]
                val end = SystemUtil.getText_Date(endTime) + " " + dayStatus[doctorDeatails.daystatustwo]
                bespeak_info_stop.text = "${start}—${end}停诊"
            }
        } else {
            bespeak_info_stop_relate.visibility = View.GONE
        }


        if (doctorDeatails.unvisitresons != null && !doctorDeatails.unvisitresons.equals("")) {
            bespeak_info_stop_hint.text = "\u3000\u3000${doctorDeatails.unvisitresons}"
        } else {
            bespeak_info_stop_hint_iv.visibility = View.GONE
        }
        if (!TextUtils.isEmpty(doctorDeatails.doctorvisiststations)) {
            ll_doc_details.visibility = View.VISIBLE
            doc_details_visittime.text = doctorDeatails.doctorvisiststations
        }

        val visitList = doctorDeatails.doctorvisits
        /**
         * 自定义出诊时间列表字段
         * visittime 0 不出诊 1上午出诊 2下午出诊 3上下午都出诊
         */
        if (visitList != null) {
            for (i in visitList.indices) {
                val visitType = visitList[i].visittype
                val visitWeek = visitList[i].visitweek
                val visitTime = visitList[i].visittime
                if (visitType != 0) {
                    if (visitTime == 0) {
                        if (doctorVisits[visitWeek].visittime === 0) {
                            doctorVisits[visitWeek].visittime = 1
                        } else if (doctorVisits[visitWeek].visittime === 2) {
                            doctorVisits[visitWeek].visittime = 3
                        }
                    } else if (visitTime == 1) {
                        if (doctorVisits[visitWeek].visittime === 0) {
                            doctorVisits[visitWeek].visittime = 2
                        } else if (doctorVisits[visitWeek].visittime === 1) {
                            doctorVisits[visitWeek].visittime = 3
                        }
                    }
                }
            }
            doctorVisitedAdapter.notifyDataSetChanged()
        }

    }
}
